package com.hunantv.mglive.ui.entertainer;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.librarymgtv.PullToRefreshBase;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseActionActivity;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.StarModel;
import com.hunantv.mglive.ui.adapter.AttentionListViewAdapter;
import com.hunantv.mglive.ui.adapter.AttentionListViewAdapter.AtteListenerCallBack;
import com.hunantv.mglive.ui.live.StarDetailActivity;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.MGTVUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.utils.UIUtil;
import com.hunantv.mglive.widget.PersonValueAnim;
import com.hunantv.mglive.widget.PullToRefreshListViewEx;

import org.json.JSONException;

import java.util.List;
import java.util.Map;

public class RecommendAttentionActivity extends BaseActionActivity implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2, AtteListenerCallBack {
    private PullToRefreshListViewEx mRecomAttenList;
    private ListView mList;
    private AttentionListViewAdapter mRecomAttenAdapter;
    private int page = 1;
    private PersonValueAnim mPersonValueAnim;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("推荐关注");
        setContentView(R.layout.activity_recommend_attention);
        initView();
        loadRecomFollows();
    }


    private void initView() {
        mPersonValueAnim = new PersonValueAnim(getContext(), (ViewGroup) UIUtil.getRootView(this));
        mRecomAttenList = (PullToRefreshListViewEx) findViewById(R.id.lv_recom_atten);
        mList = mRecomAttenList.getRefreshableView();
        mRecomAttenAdapter = new AttentionListViewAdapter(this, AttentionListViewAdapter.RECOMMEND_ATTENTION);
        mRecomAttenAdapter.setAtteClickCallBack(this);
        mRecomAttenList.setAdapter(mRecomAttenAdapter);
        mRecomAttenList.setOnItemClickListener(this);
        mRecomAttenList.setMode(PullToRefreshListViewEx.Mode.BOTH);
        mRecomAttenList.setOnRefreshListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mRecomAttenAdapter.isClickItem(view)) {
            StarModel starModel = (StarModel) parent.getAdapter().getItem(position);
            Intent intent = new Intent(this, StarDetailActivity.class);
            intent.putExtra(StarDetailActivity.KEY_STAR_ID, starModel.getUid());
            startActivity(intent);
        }
    }

    private void loadRecomFollows() {
        if (page >= 1) {
            L.d("推荐关注page", page + "");
            Map<String, String> param = new FormEncodingBuilderEx()
                    .add("uid", getUid())
                    .add("page", page + "")
                    .add("pageSize", Constant.PAGE_SIZE.toString())
                    .build();
            post(BuildConfig.URL_RCMD_STAR_LIST, param);
        }
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) throws JSONException {
        if (BuildConfig.URL_RCMD_STAR_LIST.equals(url)) {
            List<StarModel> mUserAttens = JSON.parseArray(resultModel.getData(), StarModel.class);
            if (page == 1) {
                mRecomAttenAdapter.setAttentionList(mUserAttens);
            } else if (page > 1) {
                mRecomAttenAdapter.addAttentionList(mUserAttens);
            }

            L.d("推荐关注结果", mUserAttens.size() + "");
            mRecomAttenAdapter.notifyDataSetChanged();
            mRecomAttenList.onRefreshComplete();
            if (mUserAttens.size() < Constant.PAGE_SIZE) {
                page = -1;
                mRecomAttenList.setMode(PullToRefreshListViewEx.Mode.PULL_FROM_START);
            }
        } else if (BuildConfig.URL_ADD_FOLLOW.equals(url)) {
            //关注成功，刷新粉丝
            if (followStarId != null) {
                Map<String, String> param = new FormEncodingBuilderEx()
                        .add("uid", followStarId)
                        .build();
                post(BuildConfig.URL_STAR_INFO, param);
            }

        } else if (BuildConfig.URL_STAR_INFO.equals(url)) {
            StarModel starModel = JSON.parseObject(resultModel.getData(), StarModel.class);
            for (int i = 0; i < mList.getChildCount(); i++) {
                View itemView = mList.getChildAt(i);
                Object starTagObj = itemView.getTag(R.id.star_tag);
                Object viewHoldeObj = itemView.getTag();
                if (starTagObj != null && starTagObj instanceof StarModel
                        && viewHoldeObj != null && viewHoldeObj instanceof AttentionListViewAdapter.ViewHold) {
                    StarModel tagStar = (StarModel) starTagObj;

                    if (tagStar.getUid().equals(starModel.getUid())) {
                        AttentionListViewAdapter.ViewHold viewHold = (AttentionListViewAdapter.ViewHold) viewHoldeObj;
                        viewHold.mPersonNumText.setText(starModel.getHots() + "");
                        viewHold.mFansNumText.setText(starModel.getFans() + "");
                        break;
                    }
                }
            }
//
//
//
//
//            List<StarModel> starModels = mRecomAttenAdapter.getAttentionList();
//            for (int i= 0;i<starModels.size();i++){
//                StarModel itemModle = starModels.get(i);
//                if(itemModle.getUid().equals(starModel.getUid()))
//                {
//                    itemModle.setHots(starModel.getHots());
//                    itemModle.setFans(starModel.getFans());
//                    L.d(TAG, "设置最新人气值：" + starModel.getHots());
//                    L.d(TAG,"设置最新粉丝数："+starModel.getFans());
//                    mRecomAttenAdapter.notifyDataSetChanged();
//                    break;
//                }
//
//            }
            followStarId = null;
        }
        super.onSucceed(url, resultModel);
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        mRecomAttenList.onRefreshComplete();
        super.onFailure(url, resultModel);
    }

    @Override
    public void onError(String url, Exception e) {
        mRecomAttenList.onRefreshComplete();
        super.onError(url, e);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        //下拉刷新
        page = 1;
        mRecomAttenList.setMode(PullToRefreshListViewEx.Mode.BOTH);
        loadRecomFollows();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        //上拉加载
        if (page > 0) {
            page++;
            loadRecomFollows();
        }
    }

    private String followStarId = null;

    @Override
    public boolean onClickAtte(StarModel starModel, View view) {
        if (!isLogin()) {
            MGTVUtil.getInstance().login(MaxApplication.getAppContext());
        } else {
            if (followStarId == null) {
                if (!getUid().equals(starModel.getUid())) {
                    mPersonValueAnim.startPersonValueAnim(view);
                    followStarId = starModel.getUid();
                    Map<String, String> param = new FormEncodingBuilderEx()
                            .add("uid", getUid())
                            .add("token", getToken())
                            .add("followid", starModel.getUid())
                            .build();
                    return post(BuildConfig.URL_ADD_FOLLOW, param);
                } else {
                    Toast.makeText(getContext(), "您不能粉自己哦", Toast.LENGTH_SHORT).show();
                    return false;
                }

            }
        }
        return false;
    }

    @Override
    public void onClickIcon(StarModel starModel) {
        Intent intent = new Intent(this, StarDetailActivity.class);
        intent.putExtra(StarDetailActivity.KEY_STAR_ID, starModel.getUid());
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        if (mRecomAttenAdapter != null) {
            mRecomAttenAdapter.notifyDataSetChanged();
        }
        super.onResume();
    }
}
